package com.metasoft.flex.server {

	import _2005.extended.metadata.tva.TVAMainDocument;
	import _2005.mpeg7.tva.UsageHistoryType;
	import _2005.mpeg7.tva.UserPreferencesType;
	import _2005.transport.tva.DeleteDataDocument;
	
	import com.metasoft.flex.MetasoftULC;
	import com.metasoft.flex.dto.ProfileInfo;
	import com.metasoft.flex.service.MetasoftService;
	import com.metasoft.flex.util.MetasoftHelper;
	
	import flash.net.SharedObject;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.rpc.events.ResultEvent;
	
	public class MetasoftServer {
		
		/**
		 * Check the user is valid or not
		 * @return if valid true otherwise false
		 */
		public function isValidUser(userId:String, password:String, callback:Function):void {

			/*var result:Boolean = false;
			getSingleUserProfile(userId, validate);
			
			function validate(profile:XML):void {
				
				if (profile != null) {
					if (profile.attribute("id").toString() == userId && profile.elements("password").toString()) {
						result = true;
						loadLoggedInUserProfile(userId, profile);
					}
				}
				callback(result);
			}*/
			var result:Boolean = false;
			var service:MetasoftService = new MetasoftService();
			service.getPersonalData(userId,password,onComplete);
			
			function onComplete(event:ResultEvent):void {
				
				if (event.message != null) {

					//var body:Object = MetasoftUtils.getBodyFromSOAPXML(event.message.body);
					var body:Object = event.message.body;
		        	if (body != null) {

			        	var queryResponse:Object = body.queryResponse;
			        	if (queryResponse != null) {
							var assetsArray : Array = new Array();
				        	var data:Object = queryResponse.dataArray;
				        	var targetArray :Array = new Array();
				        	if (data != null && data.length > 0 && data[0] != null) {

					        	var tVAMain:Object = data[0].TVAMain;
					        	if (tVAMain != null) {
					        		
					        		var programDescription:Object = tVAMain.programDescription;
	            					if(programDescription !=null) {
	            						
	            						var groupInfoTable:Object;
	            						groupInfoTable = programDescription.groupInformationTable;
	            						if(groupInfoTable !=null)
	            							MetasoftHelper.loadGroupInfoTable(groupInfoTable);
	            							
            							var serviceInfoTable:Object;
	            						serviceInfoTable = programDescription.serviceInformationTable;
	            						if(serviceInfoTable !=null)
	            							MetasoftHelper.loadServiceInfoTable(serviceInfoTable);
	            					}

									if (tVAMain.packageTable != null){
										assetsArray = MetasoftHelper.retrieveAssets(tVAMain.packageTable);
									}
									
									if (tVAMain.targetingInformationTable != null) {
										targetArray = MetasoftHelper.loadTargetInformationTable(tVAMain.targetingInformationTable);
									}
						        	var userDescription:Object = tVAMain.userDescriptionArray;
						        	if (userDescription != null && userDescription.length > 0 && userDescription[0] != null){

							        	var userInformationTable:Object = userDescription[0].userInformationTable;
							        	var userPreferences:Object = userDescription[0].userPreferences;
							        	var usageHistory:Object = userDescription[0].usageHistory;
							        	if (userPreferences != null) {

							        		var userIdentifier:Object = userPreferences.userIdentifier;
							        		if(userIdentifier != null) {

								        		var userIdentifierID:String = userIdentifier.name.stringValue;
								        		if ( userId == userIdentifierID) {

								        			if (userInformationTable != null) {

											        	var userInformation:Object = userInformationTable.userInformationArray;
											        	if (userInformation != null && userInformation.length > 0 && userInformation[0] != null) {

												        	var biographicInformation:Object = userInformation[0].biographicInformationArray;
												        	if (biographicInformation != null && biographicInformation.length > 0 && biographicInformation[0] != null) {

													        	var name:Object = biographicInformation[0].nameArray;
													        	if (name != null && name.length > 0 && name[0] != null) {

														        	var givenName:Object = name[0].givenNameArray;
														        	var linkingName:Object = name[0].linkingNameArray;
														        	var familyName:Object = name[0].familyNameArray;
														        	if (linkingName != null && linkingName.length > 0 && linkingName[0] != null && linkingName[0].stringValue == password) {

														        		var profileInfo:ProfileInfo = new ProfileInfo();
														        		profileInfo.age = biographicInformation[0].age;
//														        		profileInfo.gender = biographicInformation[0].gender;
																		if (biographicInformation[0].stringValue  != null &&
																			biographicInformation[0].stringValue.match("Female")) {
															        		profileInfo.gender = "Female";
																		} else {
																			profileInfo.gender = "Male";
																		}
														        		profileInfo.password = linkingName[0].stringValue;
														        		profileInfo.oldPassword = linkingName[0].stringValue;
														        		if (givenName[0] != null) {

															        		profileInfo.firstName = givenName[0].stringValue;
															        		profileInfo.userId = givenName[0].stringValue;
														        		}
														        		if (familyName != null) {

//														        			profileInfo.lastName = String(familyNameArray.getItemAt(0));
																			profileInfo.lastName = familyName[0].stringValue;
														        		}
														        		loadLoggedUserProfile(userId, profileInfo, userPreferences, usageHistory,assetsArray,targetArray);
														        		result = true;
														        	}
													        	}
												        	}
											        	}
								        			}
								        		}
							        		}
							        	}
						        	}
					        	}
				        	}
			        	}
		        	}
				}
				callback(result);
			}
		}

		/**
		 *  Clears the user session
		 */ 
	 	public function logout():void {
	 		var so:SharedObject = SharedObject.getLocal(MetasoftULC.LoggedInUser);
	 		so.clear();
	 	}
	 	
		/**
		 * Store the user profile information in local config file.
		 */ 
		public function storeProfileInfo(profileInfo:ProfileInfo,callBack:Function):void {

			// Creating profile Information
			var service:MetasoftService = new MetasoftService();
			service.modifyPersonalData(profileInfo,callBack);
		}
		
		
		private function getStringEnclosedWithQuote(str:String):String {
			return "'" + str + "'";
		}
		
		/**
		 * Registers the user with the userId,password passed along with the default profile information
		 */
		public function registerUser(regProfileInfo:ProfileInfo, callback:Function):void {

			var service:MetasoftService = new MetasoftService();
			service.uploadPersonalData(regProfileInfo, onComplete);
			
			function onComplete(event:ResultEvent):void {
//		        var body:Object = MetasoftUtils.getBodyFromSOAPXML(event.result);
		        var body:Object = event.message.body as Object;
//				var body:Object = event.result;

		        if (body == null)  {
		        	callback(false);	
		        	return;
		        }
		        body.toLocaleString()
				var upload_Result:Object = body.uploadPersonalDataResult;
		        if (upload_Result == null)  {
		        	callback(false);	
		        	return;
		        }
//		        var status:Object = upload_Result.status as Object;
//		        if (status != null && status.toString() == "success"){
//		        	callback(true);
//		        }else
//		        	callback(true);	
				var statusFlag:Number = upload_Result.serviceVersion as Number;
				var status:String = upload_Result.status;
		        if (statusFlag == 1){
		        	callback(true);
		        } else {
		        	callback(false);
		        }	
			}
			
		}
		
		/**
		 * Load all the categories in XML format
		 */
		public function loadCategories():void {
			
			if (MetasoftULC.CategoryXML == null) {
				var catXMLURL:URLRequest = new URLRequest("data/Category.xml");
				var loader:URLLoader = new URLLoader(catXMLURL);
				loader.addEventListener("complete", xmlLoaded);
	
				function xmlLoaded():void {
	    			MetasoftULC.CategoryXML = new XML(loader.data);
				}
			}
		}
		
		
		/**
	 	 * Loads the profile information of the logged in user
	 	 */
	 	public function loadLoggedUserProfile(userId:String, profileInfo:ProfileInfo, userPreferences:Object, usageHistory:Object, assetsArray : Array,targetArray:Array):void {
	 		
        	var userPreferencesType : UserPreferencesType = MetasoftHelper.processUserPreference(profileInfo, userPreferences);
        	var usageHistoryType : UsageHistoryType = MetasoftHelper.processUsageHistory(usageHistory);
        	profileInfo.userInformationTable = MetasoftHelper.processUserInformationTable(profileInfo);
        	var so:SharedObject = SharedObject.getLocal(MetasoftULC.LoggedInUser);
	        so.data.userId = userId;
	        so.data.preference = userPreferencesType;
	        profileInfo.usageHistory = usageHistoryType;
	        so.data.profileInfo = profileInfo;
	        so.data.assets = assetsArray;
	        so.data.targets = targetArray;
	   }
	   
	   /**
		 * Invokes modifyData for updating the UsageHistory
		 * Collecting the user related infomation in the background
		 * 
		 * @param profileInfo
		 */
		public function modifyUsageHistory(profileInfo:ProfileInfo):void {
			
			var service:MetasoftService = new MetasoftService();
			service.modifyUsageHistory(profileInfo);
		}

		/**
		 * Invokes submitData 
		 * 
		 * @param TVAMainDocument, Function
		 */
		public function submitData(tvaMainDoc : TVAMainDocument, callBack:Function):void {
			
			var service:MetasoftService = new MetasoftService();
			service.submitData(tvaMainDoc, callBack);
		}
		
		/** Invokes deleteData 
		 * 
		 * @param DeleteDataDocument, Function
		 */
		public function deleteData(deleteDataDoc : DeleteDataDocument, callBack:Function):void {
			
			var service:MetasoftService = new MetasoftService();
			service.deleteData(deleteDataDoc, callBack);
		}
	}
}
